<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div class="search-form isheader">
        <div>
          <a-form size="mini" :model="sheetData" layout="inline">
            <a-form-item label="所属仓库" v-if="tabsKeys==1">
              <a-select popup-container="html" class="bacClass" :style="{ width: '10rem' }" placeholder=""
                        v-model="sheetData.warehouseId"
                        allow-clear>
                <a-option v-for="item in warehouseList" :value="item.id">
                  {{ item.warehouseName }}
                </a-option>
              </a-select>
            </a-form-item>
          </a-form>
        </div>
        <div>
          <Toolbar :items="toolbarList" @select="queryHandler" @init="initInventory" @audit="auditInventorySheet"
                   @cel="delInventories" @saveData="updateInventoryDetails" @add="pageData.showAdd = true"></Toolbar>
        </div>
      </div>
      <div class="my-divisders">
        <a-divider orientation="center">
          <icon-double-up v-if="headerShow" @click="headerShow = false" :strokeWidth="2" :size="18"/>
          <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18"/>
        </a-divider>
      </div>
    </template>
    <template #pageTabel>
      <a-tabs   :lazy-load="true" type="card" :justify="true" :active-key="tabsKeys" @change="tabsChanges">
        <a-tab-pane title="盘点单列表" :key="1">
          <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true"
                           @grid-ready="sheetGridReady" style="height:calc(100% - 90px)"
                           :defaultColDef="defaultColDef" class='ag-theme-alpine' :rowData="sheetList"
                           :columnDefs="sheetColDefs" :localeText="localeText1"></AgGridVuesCopys>
          <paginationCopys :page-size-options="pagingList1" :total="sheetData.total" show-total show-jumper
                           show-page-size @change="pageChange"
                           style="justify-content: center" :page-size="sheetData.size" :current="sheetData.current"
                           @page-size-change="change"/>
        </a-tab-pane>
        <a-tab-pane title="盘点明细" :key="2">
          <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true"
                           @grid-ready="detailGridReady" style="height:calc(100% - 90px)" :defaultColDef="defaultColDef"
                           class='ag-theme-alpine'
                           :rowData="detailList" :columnDefs="inventoryColDefs"
                           :localeText="localeText1"></AgGridVuesCopys>
          <paginationCopys :page-size-options="pagingList1" :total="searchData.total" show-total show-jumper
                           show-page-size @change="pageChange1"
                           style="justify-content: center" :page-size="searchData.size" :current="searchData.current"
                           @page-size-change="change1"/>
        </a-tab-pane>
      </a-tabs>
    </template>
  </pageTabelLayout>
</template>
<script setup lang="ts">
import {ref, reactive} from "vue"
import {post, get} from "@/api/http"
import {localeText} from '@/api/aggridZw'

import Toolbar from "@/components/Toolbar.vue"
import {Message, Modal} from "@arco-design/web-vue"
import {FormInstance} from "@arco-design/web-vue/es/form";
import CorporateSectorCascader from '@/components/corporateSectorCascader/inde.vue'
import {pagingList} from "@/api/paging";

const pagingList1: any = ref(pagingList)
const headerShow = ref(true)
const auditStatus = ref(1);
const localeText1: any = ref(localeText)
const sheetList = ref([])
const detailList = ref([])
const inventoryColDefs = ref([])

const toolbarList: any = ref(['查询', '审核', '作废', '创建盘点单'])

const pager = reactive({
  total: 10,
  size: 10,
  current: 1
})


const pageData = reactive({
  showAdd: false,
  showDetails: false,
  isShow: false,
  rHeight: 0,
})

const searchData = reactive({
  id: null,
  companyId: null,
  warehouseId: '',
  warehouseType: null,
  total: 10,
  current: 1,
  size: 10
})

const sheetData = reactive({
  companyId: null,
  companyName: null,
  warehouseId: '',
  warehouseType: null,
  total: 10,
  current: 1,
  size: 10
})

const firstSheetRow = reactive({
  id: null,
  warehouseType: null
})


const warehouseList = ref([{
  warehouseName: '',
  warehouseTypeId: '',
  id: '',
}])

const loadWarehouseList = () => {
  post({
    url: 'dwWms/warehouse/getWarehouseByPara',
    data: {firmId: searchData.companyId}
  }).then(({code, data}) => {
    if (code === 200) {
      console.log(data);
      warehouseList.value = data
    }
  })
}


onMounted(() => {
  post({
    url: 'dwWms/inventorySheet/fetchUserInfoByToken',
    data: {}
  }).then(({code, message, data}) => {
    if (code === 200) {
      searchData.companyId = data.firmId;
      searchData.companyName = data.firmName;
      sheetData.companyId = data.firmId;
      sheetData.companyName = data.firmName;
      loadWarehouseList();
      loadSheetList();
    } else {
      Message.error({
        content: message,
        duration: 5000,
      });
    }
  })
});


const tabsKeys = ref(1);
const tabsChanges = (e: any) => {
  tabsKeys.value = e
  if (e == 1) {
    toolbarList.value = ['查询', '审核', '删除', '创建盘点单']
  } else if (e == 2) {
    toolbarList.value = ['保存']
  }
}


const queryHandler = () => {
  if (tabsKeys.value == 1) {
    sheetData.current = 1;
    loadSheetList();
  } else if (tabsKeys.value == 2) {
    loadInventoryList();
  }
}


const initInventory = () => {
  if (sheetData.warehouseId == '') {
    Message.warning('请先选择仓库，再进行盘点初始化')
    return;
  }
  console.log(sheetData.warehouseId, 121212);
  let wh = warehouseList.value.find(item => item.id === sheetData.warehouseId);
  post({
    url: 'dwWms/inventorySheet/createInventorySheet',
    data: {
      companyId: sheetData.companyId, companyName: sheetData.companyName,
      warehouseId: sheetData.warehouseId, warehouseName: wh.warehouseName, warehouseType: wh.warehouseTypeId
    }
  }).then(({code, message, data}) => {
    if (code === 200) {
      Message.success({
        content: "盘点单创建成功！",
        duration: 5000,
      });
      sheetData.current = 1;
      loadSheetList();
    } else {
      Message.error({
        content: message,
        duration: 5000,
      });
    }
  })
}


//盘点单列表
const sheetGridOptions = ref()
const sheetGridReady = (params: any) => {
  sheetGridOptions.value = params.api;
}

const loadSheetList = () => {
  post({
    url: 'dwWms/inventorySheet/findPagedInventorySheets',
    data: {
      companyId: sheetData.companyId, warehouseId: sheetData.warehouseId,
      current: sheetData.current, size: sheetData.size
    }
  }).then(({code, data}) => {
    if (code === 200) {
      sheetList.value = data.records;
      sheetGridOptions.value.setRowData(data.records);
      sheetData.total = data.total;
      if (tabsKeys.value == 1) {
        if (data.records.length > 0) {
          searchData.id = data.records[0].id;
          searchData.warehouseType = data.records[0].warehouseType;
          auditStatus.value = data.records[0].status;
          loadInventoryList();
        } else {
          detailGridOptions.value.setRowData(null);
        }
      }
    }
  })
}


const auditInventorySheet = () => {
  let rows = sheetGridOptions.value.getSelectedRows();
  if (rows.length === 0) {
    Message.warning("请选择需要审核的盘点单！");
    return;
  }
  if (rows[0].status != 3) {
    Message.warning("此盘点单盘点未完成或已审核，无法发起审核！");
    return;
  }
  Modal.confirm({
    title: "系统提示",
    content: "确认审核此数据?",
    onOk() {
      post({
        url: "dwWms/inventorySheet/auditInventorySheet",
        data: rows[0]
      }).then(({code, data, message}: any) => {
        if (code === 200) {
          Message.success({
            content: "审核成功",
            duration: 5000,
          });
          loadSheetList();
        } else {
          Message.warning(message);
        }
      });
    }
  });
}


//盘点单列表
const detailGridOptions = ref()
const detailGridReady = (params: any) => {
  detailGridOptions.value = params.api;
  params.columnApi.setColumnVisible('flowCardCode_1', false);
}

//根据盘点单ID和仓库类型，查询盘点明细
const loadInventoryList = () => {
  //织厂五金，染厂化工，油品，胶管
  if (searchData.warehouseType == 2 || searchData.warehouseType == 6 || searchData.warehouseType == 17
      || searchData.warehouseType == 1018 || searchData.warehouseType == 1019) {
    inventoryColDefs.value = irnChmOilRubColDefs;
  }
  //染厂成品仓  //染厂毛坯仓
  if (searchData.warehouseType == 13 || searchData.warehouseType == 18) {
    inventoryColDefs.value = endProColDefs;
  }
  //织厂原纱
  if (searchData.warehouseType == 8) {
    inventoryColDefs.value = yarnColDefs;
  }
  post({
    url: "dwWms/inventoryDetail/findPagedInventoryDetails",
    data: searchData
  })
      .then(({data, code}: any) => {
        if (code === 200) {
          detailList.value = data.records;
          detailGridOptions.value.setRowData(data.records);
          searchData.total = data.total;
        }
      })
}


//盘点明细--保存
const updateInventoryDetails = () => {
  console.log(auditStatus.value);
  if (auditStatus.value == 4) {
    Message.warning("此盘点单已审核，无法再修改！");
    return;
  }
  post({
    url: "dwWms/inventoryDetail/updateCommonInventoryDetails",
    data: detailList.value
  }).then((res: any) => {
    if (res.code === 200) {
      Message.success({
        content: "保存成功",
        duration: 5000,
      });
      loadSheetList();
      loadInventoryList();
    } else {
      Message.error({
        content: res.message,
        duration: 5000,
      });
    }
  });
};

const pageChange = (val: any) => {
  sheetData.current = val;
  loadSheetList();
}

const pageChange1 = (val: any) => {
  searchData.current = val;
  loadInventoryList();
}

function change(val: any) {
  sheetData.size = val;
  loadSheetList();
}

function change1(val: any) {
  searchData.size = val;
  loadInventoryList();
}


const delInventories = () => {
  let rows = sheetGridOptions.value.getSelectedRows()
  if (rows.length === 0) {
    Message.warning("请选择要作废的数据！");
    return;
  }
  Modal.confirm({
    title: "系统提示",
    content: "确认作废此数据?",
    onOk() {
      post({
        url: "dwWms/inventorySheet/delInventoriesByIds",
        data: rows
      }).then(({data, code}: any) => {
        if (code === 200) {
          Message.success({
            content: "作废成功",
            duration: 5000,
          });
          loadSheetList();
        }
      })
    }
  });

}


const defaultColDef = {
  sortable: true,
  resizable: true,
  filter: true,
}


const sheetColDefs = [
  {
    showRowGroup: 'hide_def',
    checkboxSelection: true,
    pinned: "left",
    width: 100,
    minWidth: 50,
    maxWidth: 50,
    lockPosition: "left",
  },
  {headerName: "盘点单号", field: "code", width: 150},
  {headerName: "公司", field: "companyName", width: 200},
  {headerName: "仓库名称", field: "warehouseName", width: 150},
  {
    headerName: "仓库类型", field: "warehouseType",
    cellRenderer: params => {
      switch (params.value) {
        case 2:
        case 7:
          return '五金仓';
        case 3:
          return '坯布仓';
        case 8:
          return '原纱仓';
        case 8:
          return '化工仓';
        case 10:
          return '油品仓';
        case 9:
          return '胶管仓';
        case 11:
          return '毛坯仓';
        case 12:
          return '成品仓';
      }
    }, width: 120
  },
  {headerName: "创建人", field: "createUser", width: 100},
  {headerName: "创建日期", field: "createTime", width: 160},
  {
    headerName: '状态', field: "status",
    cellRenderer: params => {
      switch (params.value) {
        case 1:
          return '未开始';
        case 2:
          return '进行中';
        case 3:
          return '已完成';
        case 4:
          return '已审核';
      }
    }, width: 100
  },
  {
    headerName: '操作', field: 'id',
    cellRenderer: {
      template: `
        <a-button @click="switchInventoryList">盘点</a-button>
      `,
      methods: {
        switchInventoryList() {
          searchData.current = 1;
          searchData.id = this.params.value;
          searchData.warehouseType = this.params.data.warehouseType;
          auditStatus.value = this.params.data.status;
          loadInventoryList();
          tabsChanges(2);
        }
      }
    },
    width: 100
  }

]


const irnChmOilRubColDefs = [
  {
    showRowGroup: 'hide_def',
    "checkboxSelection": true,
    "pinned": "left",
    "width": 50,
    minWidth: 50,
    maxWidth: 50,
    lockPosition: "left",
  },
  {headerName: "物料大类", field: "majorCategory", width: 150},
  {headerName: "物料小类", field: "subCategory", width: 150},
  {headerName: "物料编号", field: "materialCode", width: 150},
  {headerName: "物料名称", field: "materialName", width: 150},
  {headerName: "批次", field: "batchNo", width: 150},
  {headerName: "颜色", field: "colorName", width: 150},
  {headerName: "规格", field: "specification", width: 100},
  {headerName: "初始数量", field: "initCount", width: 120},
  {
    headerName: "实际数量", field: "realCount", editable: true,
    cellRenderer: (params) => {
      return "<span style = 'padding:20px;background:#00ffff'>" + params.value + '</span>';
    }, width: 150
  },
  {
    headerName: "差异数量", field: "diffCount",
    valueGetter: params => {
      params.data.diffCount = params.data.realCount - params.data.initCount;
      return params.data.diffCount;
    }, width: 120
  },
  {headerName: "单位", field: "unit", width: 100}
]


const yarnColDefs = [
  {
    showRowGroup: 'hide_def',
    checkboxSelection: true,
    pinned: "left",
    width: 50,
    minWidth: 50,
    maxWidth: 50,
    lockPosition: "left",
  },
  {headerName: "物料大类", field: "majorCategory", width: 120},
  {headerName: "物料小类", field: "subCategory", width: 120},
  {headerName: "物料编号", field: "materialCode", width: 150},
  {headerName: "物料名称", field: "materialName", width: 150},
  {headerName: "批次", field: "batchNo", width: 150},
  {headerName: "初始整件数量", field: "initWholeCount", width: 150},
  {headerName: "初始散件数量", field: "initBulkCount", width: 150},
  {headerName: "初始总数量", field: "initCount", width: 120},
  {
    headerName: "实际整件数量", field: "realWholeCount", editable: true,
    cellRenderer: (params) => {
      return "<span style = 'padding:20px;background:#00ffff'>" + params.value + '</span>';
    }, width: 150
  },
  {
    headerName: "实际散件数量", field: "realBulkCount", editable: true,
    cellRenderer: (params) => {
      return "<span style = 'padding:20px;background:#00ffff'>" + params.value + '</span>';
    }, width: 150
  },
  {
    headerName: "实际总数量", field: "realCount",
    valueGetter: params => {
      params.data.realCount = parseFloat(params.data.realWholeCount) + parseFloat(params.data.realBulkCount);
      return params.data.realCount;
    }, width: 120
  },
  {
    headerName: "差异数量", field: "diffCount",
    valueGetter: params => {
      params.data.diffCount = params.data.realCount - params.data.initCount;
      return params.data.diffCount;
    }, width: 120
  },
  {headerName: "仓位", field: "location", width: 100}
]


//染厂成品仓明细
const endProColDefs = [
  {
    showRowGroup: 'hide_def',
    "checkboxSelection": true,
    "pinned": "left",
    "width": 50,
    minWidth: 50,
    maxWidth: 50,
    lockPosition: "left",
  },
  {headerName: "流转卡号", field: "flowCardCode", width: 150},
  {headerName: "布号", field: "clothCode", width: 150},
  {headerName: "品名", field: "productName", width: 100},
  {headerName: "色号", field: "colorCode", width: 150},
  {headerName: "色称", field: "colorName", width: 150},
  {headerName: "匹号", field: "pieceNo", width: 100},
  {headerName: "条形码", field: "barCode", width: 150},
  {headerName: "初始匹数", field: "pieceCount", width: 120},
  {
    headerName: "实际匹数", field: "realCount", editable: true,
    cellRenderer: (params) => {
      return "<span style = 'padding:20px;background:#00ffff'>" + params.value + '</span>';
    }, width: 150
  },
  {
    headerName: "差异数量", field: "diffCount",
    valueGetter: params => {
      params.data.diffCount = params.data.realCount - params.data.pieceCount;
      return params.data.diffCount;
    }, width: 120
  }
]

</script>
<script lang="ts">
export default {
  name: "ProductInStock",
}
</script>

<style scoped>
.arco-select-dropdown {
  width: 150px;
}
</style>


<script setup lang="ts">
</script>